package LandR.personal.personalServlet;


import LandR.personal.personalHelp.Users.User;
import LandR.personal.personalHelp.function_jsp.JspPageUseMethod;
import token.TokenHelp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet {
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8"); // 响应文本格式， json格式
        response.setCharacterEncoding("utf-8"); // 编码格式
        request.setCharacterEncoding("utf-8");//设置请求的编码格式


        JspPageUseMethod jpum = new JspPageUseMethod();
        String path = (String) this.getServletContext().getAttribute("path");
        Integer ID = -1;
        String token = request.getHeader("token");

        token = token.substring(token.indexOf("\"") + 1, token.lastIndexOf("\""));
        System.out.println("前端传递的token令牌是：" + token);

        TokenHelp th = new TokenHelp();
        try {
            ID = th.judgeToken(token);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ID != -1) {
            User user1 = new User();
            user1.setId(ID);
            try {
                user1 = jpum.selectUserData(user1);
                user1.setId(ID);
                user1.setImageAddress(path);
                jpum.updateUserData(user1);
                PrintWriter out = response.getWriter();
                out.print("头像上传成功");
                System.out.println("图片信息更新成功");
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("失败！token已过期或token不匹配！");
            PrintWriter out = response.getWriter();
            out.print("失败！token已过期或token不匹配！");
        }


    }


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPut(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
